<script setup lang="ts">
import { computed } from "vue";
import type {
  FormDesignerComponents,
  FormItemPerm
} from "../FormComponentMixin";
import { isReadonly } from "../FormItem";
import { api } from "@/api/common/index";
const props = defineProps({
  type: {
    type: String,
    default: ""
  },
  mode: {
    type: String,
    default: "normal" //组件模式，free设计模式，normal 编辑模式, read 阅读模式，disable 禁用模式
  }
});

const _value = defineModel<string>();
const config = defineModel<FormDesignerComponents>("config");
const perm = inject<Array<FormItemPerm>>("perm");
const emits = defineEmits(["change"]);
const options = ref([]);

const disabled = computed(() => {
  if (props.mode === "disable" && isReadonly(perm, config.value.code)) {
    return true;
  }
  return false;
});

onMounted(() => {
  if (config.value.props.optionType === "0") {
    options.value = config.value.props.options;
  } else {
    api(config.value.props.optionUrl, {}).then(res => {
      if (res.code === 200) {
        options.value = res.data.map(item => {
          return {
            label: item[config.value.props.optionLabel],
            value: item[config.value.props.optionValue]
          };
        });
      }
    });
  }
});

const handleValueChange = val => {
  emits("change", config.value, val);
};
</script>

<template>
  <el-radio-group
    v-if="config.props.expanding"
    v-model="_value"
    :disabled="disabled"
    @change="handleValueChange"
  >
    <el-radio
      v-for="(op, i) in options"
      :key="i"
      :label="op.label"
      :value="op.value"
    />
  </el-radio-group>
  <el-select
    v-else
    v-model="_value"
    :disabled="disabled"
    @change="handleValueChange"
  >
    <el-option
      v-for="(op, i) in options"
      :key="i"
      :label="op.label"
      :value="op.value"
    />
  </el-select>
</template>

<style scoped></style>
